#!/usr/bin/env python
#coding=utf-8

from __future__ import division
import time,datetime
import sys
from define import BASE_DIR
sys.path.append(BASE_DIR)

from lib.abstract_cron import abstract_cron
from lib.func_ext import dateTypeInterval,str2sec,sec2str,ksort

#需要修改
class business_api_day(abstract_cron) :

    #需要修改
    noLock = True   #是否生成脚本锁文件
    selectTable = 'sdb_statistics_business_api_hour'
    insertTable = 'sdb_statistics_business_api_day'

    def __init__(self) :
        #需要修改
        super(business_api_day,self).__init__(__file__)

    def boot(self,timestamp=[]) :
        #self.preBoot()

        sql = self.getSelectSql(timestamp)
        row = self.db.select(sql)

        if row :
            self.writeSql(sql,'succ','select')
            for v in row :
                v['calltime'] = str2sec(time.strftime('%Y-%m-%d'),'%Y-%m-%d')-1*24*3600
                #计算成功率
                v['sum_fail'] = v['sum'] - v['sum_succ']
                self.figureRatio(v,'sum','sum_fail','api_succ_ratio')
                #数据过滤
                self.filterItems(v)

            #批量插入
            self.doBatchExec()
        else :
            self.writeSql(sql,'fail','select')
        self.sufBoot()
        print 'ok'

    def getSelectSql(self,timestamp=[]) :
        timeFilter = self.getTimeFilter()
        sql = 'SELECT `from_node_id`,`from_node_type`,`to_node_id`,`to_node_type`,'
        sql += ' SUM(`sum`) AS sum,SUM(`sum_succ`) AS sum_succ,`api`,`date` AS day'
        sql += ' FROM '+self.selectTable
        sql += ' WHERE '+self.db._filter(timeFilter)
        sql += ' GROUP BY `from_node_id`,`to_node_id`,`api`,`date`'
        return sql


    def getTimeFilter(self) :
        keyFilter = {}
        time_begin = str(sec2str('%Y%m%d',time.time()-1*24*3600))
        time_end = str(sec2str('%Y%m%d',time.time()))
        keyFilter['date|between'] = [time_begin,time_end]
        return keyFilter

    def insertKeys(self) :
        return ['from_node_id','from_node_type','to_node_id',
                'to_node_type','sum','sum_succ','api_succ_ratio',
                'api','day','calltime','sum_fail']

if __name__ == '__main__' :
    obj = business_api_day()
    obj.boot()